package com.junzhiit.nengji.shop.service.impl;

import java.util.Date;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.cache.UserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.shop.service.SendPhoneService;
import com.junzhiit.nengji.shop.web.exception.LimitControlException;
import com.junzhiit.nengji.shop.web.exception.MobilePhoneIsExistException;
import com.junzhiit.nengji.shop.web.exception.SendSMSFaileException;
import com.junzhiit.nengji.shop.web.exception.UserNotFoundException;
import com.junzhiit.nengji.shop.web.util.aliyun.SmsUtil;
import com.junzhiit.nengji.shop.web.util.aliyun.bean.SMSParams;
import com.junzhiit.nengji.shop.web.vo.ResultVO;

@Service
public class SendPhoneServiceImpl extends BaseServiceImpl implements SendPhoneService {

	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private UserCacheDAO userCacheDAO;

	@Override
    public ResultVO sendPhoneCodeByUserId(String userId,String smsModel){
		User user=userDAO.query(userId);
		if(user==null){
			throw new UserNotFoundException("用户未找到");
		}
		String mobilePhone=user.getMobilePhone();
		
		ResultVO result = new ResultVO();
		String key = DIYKey.getMobilePhoneCodeKey(mobilePhone);
		String randCode = RandomStringUtils.randomNumeric(6);
		SMSParams sms = new SMSParams();
		sms.setSignName(SmsUtil.ALIYUN_SMS_SIGN_NAME);
		sms.setTemplateCode(smsModel);
		sms.setPhoneNumbers(new String[] { mobilePhone });
		sms.setParamKeys(new String[] {SmsUtil.KEY_VERIFICATION_CODE });
		sms.setParamValues(new String[] { randCode });
		boolean sendSucceed = false;
		try {
			SendSmsResponse response = SmsUtil.sendSms(sms);
			if (response.getCode() != null && response.getCode().equals("OK")) {
				sendSucceed = true;
			}else if(response.getCode() != null && response.getCode().equals(SmsUtil.LIMIT_CONTROL_ERROR)){
				throw new LimitControlException("不能过于频繁发送验证码,请稍后再发");
			}
		} catch (ClientException e) {
			e.printStackTrace();
		}
		if (sendSucceed) {
			// 设置验证码有效时间为10分钟
			Date date = DateUtil.addMins(new Date(), 10);
			SmsUtil.RandCode code = new SmsUtil.RandCode();
			code.setCode(randCode);
			code.setTimestamp(date.getTime());
			userCacheDAO.addHash(key, code);
		} else {
			throw new SendSMSFaileException("无法发送手机验证码");
		}
		return result;
	}
    
	@Override
    public ResultVO sendPhoneCode(String mobilePhone,String smsModel){
		ResultVO result = new ResultVO();
		String key = DIYKey.getMobilePhoneCodeKey(mobilePhone);
		String randCode = RandomStringUtils.randomNumeric(6);
		SMSParams sms = new SMSParams();
		sms.setSignName(SmsUtil.ALIYUN_SMS_SIGN_NAME);
		sms.setTemplateCode(smsModel);
		sms.setPhoneNumbers(new String[] { mobilePhone });
		sms.setParamKeys(new String[] {SmsUtil.KEY_VERIFICATION_CODE });
		sms.setParamValues(new String[] { randCode });
		boolean sendSucceed = false;
		try {
			SendSmsResponse response = SmsUtil.sendSms(sms);
			if (response.getCode() != null && response.getCode().equals("OK")) {
				sendSucceed = true;
			}else if(response.getCode() != null && response.getCode().equals(SmsUtil.LIMIT_CONTROL_ERROR)){
				throw new LimitControlException("不能过于频繁发送验证码,请稍后再发");
			}
		} catch (ClientException e) {
			e.printStackTrace();
		}
		if (sendSucceed) {
			// 设置验证码有效时间为10分钟
			Date date = DateUtil.addMins(new Date(), 10);
			SmsUtil.RandCode code = new SmsUtil.RandCode();
			code.setCode(randCode);
			code.setTimestamp(date.getTime());
			userCacheDAO.addHash(key, code);
		} else {
			throw new SendSMSFaileException("无法发送手机验证码");
		}
		return result;
	}
    
	@Override
    public ResultVO sendPhoneCodeByUserId(String userId, String mobilePhone,String smsModel) {
		ResultVO result = new ResultVO();

		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到");
		}

		User param = userDAO.checkMobilePhone(mobilePhone);
		if (param != null) {
			String phone = user.getMobilePhone();
			if (!StringUtils.isNotBlank(phone) || (StringUtils.isNotBlank(phone) && !phone.equals(mobilePhone))) {
				throw new MobilePhoneIsExistException("号码已被使用");
			}
		}

		String randCode = RandomStringUtils.randomNumeric(6);

		SMSParams sms = new SMSParams();
		sms.setSignName(SmsUtil.ALIYUN_SMS_SIGN_NAME);
		sms.setTemplateCode(smsModel);
		sms.setPhoneNumbers(new String[] { mobilePhone });
		sms.setParamKeys(new String[] { SmsUtil.KEY_VERIFICATION_CODE });
		sms.setParamValues(new String[] { randCode });

		boolean sendSucceed = false;
		try {
			SendSmsResponse response = SmsUtil.sendSms(sms);
			if (response.getCode() != null && response.getCode().equals("OK")) {
				sendSucceed = true;
			}
		} catch (ClientException e) {
			e.printStackTrace();
		}
		if (sendSucceed) {
			// 设置验证码有效时间为10分钟
			Date time = DateUtil.addMins(new Date(), 10);

			SmsUtil.RandCode code = new SmsUtil.RandCode();
			code.setCode(randCode);
			code.setTimestamp(time.getTime());

			String key = DIYKey.getMobilePhoneCodeKey(mobilePhone);
			result.setData(userCacheDAO.addHash(key, code));
		} else {
			throw new SendSMSFaileException("发送手机验证码失败");
		}
		return result;
	}
}
